package shop_cart

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"order_bff/controller"
	"order_bff/forms"
	"order_bff/global"
	"order_bff/goods_proto"
	"order_bff/inventory_proto"
	"order_bff/order_proto"
	"strconv"
)

// 购物车列表
func List(c *gin.Context) {
	//userId, _ := c.Get("userId")
	id := c.Query("user_id")
	userId, _ := strconv.Atoi(id)
	list, err := global.OrderSrvConnect.CartItemList(context.Background(), &order_proto.UserInfo{UserId: int32(userId)})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	ids := make([]int32, 0)
	for _, response := range list.ShopCartInfo {
		ids = append(ids, response.GoodsId)
	}
	if len(ids) == 0 {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "查询为空",
			"data": nil,
		})
		return
	}
	goods, err := global.GoodsSrvConnect.BatchGetGoods(context.Background(), &goods_proto.BatchGoodsIdInfo{Id: ids})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	goodsList := make([]interface{}, 0)
	for _, response := range list.ShopCartInfo {
		for _, datum := range goods.Data {
			if datum.Id == response.GoodsId {
				tmpMap := map[string]interface{}{}
				tmpMap["id"] = response.Id
				tmpMap["goods_id"] = response.GoodsId
				tmpMap["good_name"] = datum.Name
				tmpMap["good_image"] = datum.GoodsFrontImage
				tmpMap["good_price"] = datum.ShopPrice
				tmpMap["nums"] = response.Num
				tmpMap["checked"] = response.Checked
				goodsList = append(goodsList, tmpMap)
			}
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "查询为空",
		"data": map[string]interface{}{
			"total":     list.Total,
			"goodsList": goodsList,
		},
	})
}

// 添加购物车
func Add(c *gin.Context) {
	itemForm := forms.ShopCartItemForm{}
	if err := c.ShouldBind(&itemForm); err != nil {
		controller.ReturnErrorJson(err, c)
		return
	}
	//查询商品是否存在
	_, err := global.GoodsSrvConnect.GetGoodsDetail(context.Background(), &goods_proto.GoodInfoRequest{Id: itemForm.GoodsId})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	//查询商品库存
	detail, err := global.InventorySrvConnect.InvDetail(context.Background(), &inventory_proto.GoodsInvInfo{GoodsID: itemForm.GoodsId})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	if detail.Nums < itemForm.Nums {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "库存不足",
			"data": nil,
		})
		return
	}
	//userId, _ := c.Get("userId")
	id := c.PostForm("user_id")
	userId, _ := strconv.Atoi(id)
	//添加到购物车
	item, err := global.OrderSrvConnect.CreateCartItem(context.Background(), &order_proto.CartItemRequest{
		UserId:  int32(userId),
		GoodsId: itemForm.GoodsId,
		Num:     itemForm.Nums,
	})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "创建成功",
		"data": item.Id,
	})
}

// 修改购物车
func Update(c *gin.Context) {
	//userId, _ := c.Get("userId")
	id := c.PostForm("user_id")
	userId, _ := strconv.Atoi(id)
	itemForm := forms.ShopCartItemUpdateForm{}
	if err := c.ShouldBind(&itemForm); err != nil {
		controller.ReturnErrorJson(err, c)
		return
	}
	//查询商品库存
	detail, err := global.InventorySrvConnect.InvDetail(context.Background(), &inventory_proto.GoodsInvInfo{GoodsID: itemForm.GoodsId})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	if detail.Nums < itemForm.Nums {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "库存不足",
			"data": nil,
		})
		return
	}
	//调用修改订单
	_, err = global.OrderSrvConnect.UpdateCartItem(context.Background(), &order_proto.CartItemRequest{
		UserId:  int32(userId),
		GoodsId: itemForm.GoodsId,
		Num:     itemForm.Nums,
		Checked: false,
	})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "修改成功",
		"data": nil,
	})
}

// 删除购物车
func Delete(c *gin.Context) {
	goodsId := c.PostForm("goods_id")
	userId := c.PostForm("user_id")
	goodsIdInt, _ := strconv.Atoi(goodsId)
	userIdInt, _ := strconv.Atoi(userId)
	_, err := global.OrderSrvConnect.DeleteCartItem(context.Background(), &order_proto.CartItemRequest{
		UserId:  int32(userIdInt),
		GoodsId: int32(goodsIdInt),
	})
	if err != nil {
		controller.HandleGrpcErrorToHttp(err, c)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "删除成功",
		"data": nil,
	})
}
